package com.junbao.message.ui.listener;

import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.junbao.commom.context.BeanFactory;
import com.junbao.commom.context.ClassPathXmlApplicationContext;
import com.junbao.message.application.service.TaskService;

/**
 * 消息重发监听器
 * 启动：
 *    该监听器会定时获取待发送的消息向被动方进行消息重发
 *    该监听器只启动一次，启动条件为服务器重启才会启动，
 *    默认加载待发送的消息，并将消息置为发送中
 * 结束：
 *    将所有发送中的状态置为待发送的状态
 * 
 * @author yilin
 *
 */
@WebListener
public class MessageRetrySendListener implements ServletContextListener{

	//日志输出
	private static final Logger LOGGER = LoggerFactory.getLogger(MessageConfirmSendFlagListener.class);
		
	private final ScheduledExecutorService scheduler =  Executors.newScheduledThreadPool(1, new ThreadFactory() {
		
		@Override
		public Thread newThread(Runnable r) {
			Thread thread = new Thread(r,"MessageRetrySendListener");
			thread.setDaemon(true);
			return null;
		}
	});
		
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		
		long nextExecuteTime = initDay();
		long initTime = nextExecuteTime - new Date().getTime();
		
		scheduler.scheduleAtFixedRate(new Runnable() {
			@Override	
			public void run() {
				try {
					BeanFactory beanFactory = ClassPathXmlApplicationContext.getInstance();	
					TaskService taskService = (TaskService) beanFactory.getBean("taskService");
					taskService.messageRetrySendListener();
				} catch (Exception e) {
					LOGGER.error("消息重发监听器异常！", e);
				}
			}
		}, initTime, 1000*60*1, TimeUnit.MILLISECONDS);
	}
	
	//监听结束
	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		scheduler.shutdown();
		BeanFactory beanFactory = ClassPathXmlApplicationContext.getInstance();	
		TaskService taskService = (TaskService) beanFactory.getBean("taskService");
		taskService.messageStatusToWaitSendFromSendingUpdate();
		LOGGER.info("MessageRetrySendListener shutdown...");
	}
	
	private static long initDay() {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY)+1);
		Date time = calendar.getTime();
		return time.getTime();
	}
	
}
